package com.example.music_player_app.ui.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.music_player_app.Bean.PersonalizedResult;
import com.example.music_player_app.Bean.SongDetail;
import com.example.music_player_app.MainActivity;
import com.example.music_player_app.R;
import com.example.music_player_app.api.service.playList.PersonalizedService;
import com.example.music_player_app.api.service.playList.SearchService;
import com.example.music_player_app.api.service.playList.SongUrlService;
import com.example.music_player_app.databinding.FragmentHomeBinding;
import com.example.music_player_app.ui.playListDetail.MySongAdapter;
import com.example.music_player_app.ui.playListDetail.PlayListDetail;
import com.example.music_player_app.ui.playSong.PlaySong;
import com.example.music_player_app.utils.ApiServer;
import com.example.music_player_app.utils.CookieServer;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;
    private View root ;
    private SharedPreferences sp;
    private SearchView searchView;
    private List<SongDetail> songList = new ArrayList<>(); // 搜索歌曲列表

    private ListView listView; // 推荐歌单列表
    List<PersonalizedResult> list = new ArrayList<>(); // 推荐歌单数据

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        root = binding.getRoot();

        listView = binding.listView;
        searchView = binding.indexSearch;
        initPersonalized(); // 初始化推荐歌单

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if(query.equals("")) {
                    Toast.makeText(getContext(),"请输入要搜索的歌曲",Toast.LENGTH_LONG).show();
                    return false;
                } else {
                    searchSong(query, 30);
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                System.out.println("字改了");
                return false;
            }
        });


        return root;
    }

    // 搜索
    private void searchSong(String query, int i) {
        //创建意图对象
        Intent intent = new Intent(getContext(),PlayListDetail.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean("isSearch",true);
        bundle.putString("searchQuery", query);
        intent.putExtra("searchData",bundle);
        startActivity(intent);
    }

    private void initPersonalized() {
        new Thread(){
            @Override
            public void run() {
                ApiServer http = new ApiServer();
                PersonalizedService personalizedService = http.getRetrofit().create(PersonalizedService.class);
                Call<ResponseBody> call = personalizedService.get(CookieServer.getCookie(), 10);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            JSONObject jsonObject = (JSONObject) JSONObject.parse(response.body().string());
                            JSONArray array = jsonObject.getJSONArray("result");
                            for(int i=0;i<array.size();i++) {
                                // 添加res到list中
                                PersonalizedResult result = JSON.parseObject(JSON.toJSONString(array.get(i)), PersonalizedResult.class);
                                list.add(result);
                            }
                            listView.setAdapter(new MyAdapter(list, getActivity()));
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    System.out.println(position);
                                    //创建意图对象
                                    Intent intent = new Intent(getContext(),PlayListDetail.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putLong("id",list.get(position).getId());
                                    intent.putExtra("data",bundle);
                                    startActivity(intent);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.i("fail", "onFailure: " + t);
                    }
                });
            }
        }.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}